package com.example.todolist.service.impl;

import com.example.todolist.entity.Teaching;
import com.example.todolist.mapper.TeachingMapper;
import com.example.todolist.service.TeachingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class TeachingServiceImpl implements TeachingService {
    @Autowired
    private TeachingMapper teachingMapper;

    @Override
    public List<Teaching> getAll() {
        return teachingMapper.getAll();
    }

    @Override
    public boolean updateQuestion(Integer userId, Integer deviceId, String type, String question) {
        Teaching existingTeaching = teachingMapper.getAnswer(userId, deviceId, type);
        if (existingTeaching == null) {
            // 如果记录不存在，则插入新记录
            Teaching newTeaching = new Teaching();
            newTeaching.setUserId(userId);
            newTeaching.setDeviceId(deviceId);
            newTeaching.setType(type);
            newTeaching.setQuestion(question);
            // answer 字段在插入时可以为空或者根据需要设置默认值
            newTeaching.setAnswer(""); // 默认设置为空字符串，可根据实际需求调整
            return teachingMapper.insert(newTeaching) > 0;
        } else {
            // 如果记录存在，则更新question字段
            return teachingMapper.updateQuestion(userId, deviceId, type, question) > 0;
        }
    }

    @Override
    public boolean updateAnswer(Integer userId, Integer deviceId, String type, String answer) {
        Teaching existingTeaching = teachingMapper.getAnswer(userId, deviceId, type);
        if (existingTeaching == null) {
            // 如果记录不存在，则插入新记录
            Teaching newTeaching = new Teaching();
            newTeaching.setUserId(userId);
            newTeaching.setDeviceId(deviceId);
            newTeaching.setType(type);
            newTeaching.setAnswer(answer);
            // question 字段在插入时可以为空或者根据需要设置默认值
            newTeaching.setQuestion(""); // 默认设置为空字符串，可根据实际需求调整
            return teachingMapper.insert(newTeaching) > 0;
        } else {
            // 如果记录存在，则更新answer字段
            return teachingMapper.updateAnswer(userId, deviceId, type, answer) > 0;
        }
    }

    @Override
    public Teaching getAnswer(Integer userId, Integer deviceId, String type) {
        return teachingMapper.getAnswer(userId, deviceId, type);
    }

    @Override
    public boolean clearAllTeachingData() {
        return teachingMapper.deleteAll() > 0;
    }
} 